package com.yyc.hkpost.ui.newfrg

import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.text.Editable
import android.text.TextWatcher
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.Observer
import androidx.lifecycle.viewModelScope
import com.blankj.utilcode.util.TimeUtils
import com.kingja.loadsir.core.LoadService
import com.yyc.hkpost.R
import com.yyc.hkpost.api.UIHelper
import com.yyc.hkpost.base.BaseFragment
import com.yyc.hkpost.bean.RfidStateBean
import com.yyc.hkpost.bean.db.RfidBean
import com.yyc.hkpost.databinding.FRfidParentBinding
import com.yyc.hkpost.ext.SCAN_STATUS_QRCODE
import com.yyc.hkpost.ext.ZKING_ADD_TYPE
import com.yyc.hkpost.ext.ZKING_TYPE
import com.yyc.hkpost.ext.bindViewPager2
import com.yyc.hkpost.ext.init
import com.yyc.hkpost.mar.eventViewModel
import com.yyc.hkpost.util.MusicUtils
import com.yyc.hkpost.viewmodel.AssetModel
import com.yyc.hkpost.viewmodel.RfidListModel
import com.yyc.hkpost.viewmodel.RfidModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import me.hgj.jetpackmvvm.ext.nav

/**
 * User: Nike
 *  2024/10/10 09:49
 */
class RfidParentFrg: BaseFragment<RfidListModel, FRfidParentBinding>() {

    lateinit var loadsir: LoadService<Any>

    var parentId: Long = 0

    var parentIdString: String = ""

    var title: String = ""

    var location: String = ""

    var prefix: String? = null

    var containsPrefix: Boolean = false

    val assetModel: AssetModel by activityViewModels()

    val rfidModel: RfidModel by activityViewModels()

    val rfidListModel: RfidListModel by activityViewModels()

    var position: Int = 0

    var fragments: ArrayList<Fragment> = arrayListOf()

    override fun initView(savedInstanceState: Bundle?) {
        arguments?.let {
            parentId = it.getLong("parentId")
            position = it.getInt("position")
            title = it.getString("title").toString()
            location = it.getString("location").toString()
            prefix = it.getString("prefix").toString()
            parentIdString = String.format("%06d", parentId)
        }
        mDatabind.viewmodel = mViewModel
        mDatabind.click = ProxyClick()
        mViewModel.backTitle.set("$parentIdString" + " " + "(0)")
        mViewModel.epcPrefix.set("：" + if (!prefix.isNullOrEmpty()) prefix else "NO")
        mDatabind.includeViewpager.viewpagerLinear.setBackgroundColor(ContextCompat.getColor(requireContext(), android.R.color.transparent))
        MusicUtils.init(requireActivity())

        setViewPage()

        mDatabind.etText.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
            }

            override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
                rfidListModel.searchText.value = p0.toString()
            }

            override fun afterTextChanged(p0: Editable?) {
            }
        })

        lifecycle.addObserver(object : DefaultLifecycleObserver {

            override fun onDestroy(owner: LifecycleOwner) {
                super.onDestroy(owner)
                rfidModel.isOpen.value = false
                assetModel.epcData.value = null
                rfidModel.scanData.value = null
                rfidListModel.epcUploadData.value = null
                MusicUtils.clear()
            }

            override fun onPause(owner: LifecycleOwner) {
                super.onPause(owner)
                isOpenRfid(false)
                assetModel.epcData.value = null
                rfidModel.scanData.value = null
            }
        })
    }

    //region 设置viewpager
    private fun setViewPage() {
        var bundle = Bundle()
        bundle.putLong("parentId", parentId)
        bundle.putString("parentIdString", parentIdString)
        bundle.putString("prefix", prefix)
        bundle.putInt("position", position)

        val rfidAllFrg = RfidAllFrg()
        rfidAllFrg.arguments = bundle
        fragments.add(rfidAllFrg)

        val rfidMatchFrg = RfidMatchFrg()
        rfidMatchFrg.arguments = bundle
        fragments.add(rfidMatchFrg)

        mDatabind.includeViewpager.viewPager.init(this, fragments)
        var mTitles =
            arrayListOf(
                getString(R.string.all),
                getString(R.string.match),
            )

        mDatabind.includeViewpager.magicIndicator.bindViewPager2(
            mDatabind.includeViewpager.viewPager,
            mTitles
        )
        mDatabind.includeViewpager.viewPager.offscreenPageLimit = mTitles.size
    }
    //endregion

    inner class ProxyClick() {

        fun toRfid(){
            isOpenRfid(if (mDatabind.fbRfid.labelText.equals(getString(R.string.rfid_off)))false else true)
            mDatabind.fbMenu.close(false)
        }

        fun toSave(){
            mViewModel.viewModelScope.launch(Dispatchers.IO) {
                val all = mViewModel.rfidDao.findAll(parentId)
                withContext(Dispatchers.Main) {
                    isOpenRfid(false)
                    mViewModel.setSave(all, parentIdString, position, location, title, prefix)
                    mDatabind.fbMenu.close(true)
                }
            }
        }

        fun onClose(){
            nav().navigateUp()
        }

        fun onZking(){
            UIHelper.startZxingAct(ZKING_TYPE)
        }

        fun onAdd(){
            UIHelper.startZxingAct(ZKING_ADD_TYPE)
        }

    }

    override fun createObserver() {
        super.createObserver()
        rfidListModel.mutableTitle.observe(viewLifecycleOwner, {
            mViewModel.backTitle.set("$parentIdString" + " " + "( " + it + " )")
        })

        mViewModel.isLoaddingBean.observe(viewLifecycleOwner, Observer{
            if (it.isLoading){
                showLoading(getString(R.string.text14))
            }else{
                Handler(Looper.getMainLooper()).postDelayed({
                    dismissLoading()
                }, 1000)
            }
        })

        eventViewModel.zkingType.observeInFragment(this, Observer {
            if (it.type == ZKING_ADD_TYPE){
                assetModel.epcData.value = RfidStateBean(
                    tagId = it.text,
                    scanStatus = SCAN_STATUS_QRCODE,
                    rssi = "0"
                )
            }
        })

        assetModel.epcData.observe(viewLifecycleOwner, {
            if (it == null) return@observe
            mViewModel.viewModelScope.launch(Dispatchers.IO) {
                if (!prefix.isNullOrEmpty()){
                    containsPrefix = prefix!!.split(",").any { s ->
                        it.tagId!!.startsWith(s, ignoreCase = true)
                    }
                }
                //判断重复
                var rfidBean = mViewModel.rfidDao.findParentIdBean(parentId, it.tagId!!)
                if (rfidBean == null){
                    rfidBean = RfidBean()
                    rfidBean.epc = it.tagId
                    rfidBean.crearDate = TimeUtils.getNowString()
                    rfidBean.parentId = parentId
//                    rfidBean.position = adapter.data.size + 1
                    mViewModel.rfidDao.add(rfidBean)

                    rfidBean.status = if (containsPrefix) 1 else 0
                    //符合EPC前缀
                    if (containsPrefix){
                        MusicUtils.play()
                    }
                    rfidListModel.epcUploadData.postValue(rfidBean)
                }
            }
        })
    }

    fun isOpenRfid(isOpen: Boolean){
        if (isOpen){
            rfidModel.isOpen.postValue(true)
            mDatabind.fbRfid.labelText = getString(R.string.rfid_off)
        }else{
            rfidModel.isOpen.postValue(false)
            mDatabind.fbRfid.labelText = getString(R.string.rfid_on)
        }
    }

}